import tools from '../utils/tools'
import CryptoJS from '../utils/crypto-js/index'

export default class miniBridge {
    constructor() {
        this.platform = 'mini'
        this._readyPromise = new Promise(resolve => {
            if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {
                document.addEventListener('WeixinJSBridgeReady', resolve, false)
            } else {
                resolve()
            }
        })
    }

    onReady() {
        return this._readyPromise
    }

    back(params) {
        wx.miniProgram.navigateBack(params)
    }

    // 更新分享信息
    updateShareData(params) {
        wx.miniProgram.postMessage({
            data: {
                type: 'updateShareData',
                ...params
            }
        });
    }

    // 打开一个新的专题页面
    goZhuanti(url) {
        this.navigateTo({
            url: '/pages/richText/headlessWebview?url=' + encodeURIComponent(Config.host + url)
        })
    }

    navigateTo(params) {
        wx.miniProgram.navigateTo(params);
    }

    reLaunch(params) {
        wx.miniProgram.reLaunch(params);
    }

    // 更新页面标题，小程序无效果，只是为了统一api
    setTitle(title) {
        setTimeout(function () {
          document.title = title
          var i = document.createElement("iframe")
          i.src = "./favicon.ico"
          i.style.display = "none"
          i.onload = function () {
            setTimeout(function () {
              i.remove()
            }, 9)
          }
          document.body.appendChild(i)
        }, 1)
    }

    getUserInfo() {
        if (this.userInfo) return this.userInfo
        try {
            let u = decodeURIComponent(tools.getRouteQuery().u || '')
            if (!u) return {}
            const plainText = CryptoJS.AES.decrypt(u, 'xkafrontendgroup')
            this.userInfo = JSON.parse(plainText.toString(CryptoJS.enc.Utf8))
            return this.userInfo
        } catch (e) {
            return {
                uid: ''
            }
        }
    }
}
